<template>
  <div class="add-project-container">
    <el-form
      ref="formRef"
      :model="form"
      :rules="formRules"
      label-position="top"
    >
      <el-form-item prop="name" label="项目名称">
        <el-input v-model="form.name" placeholder="项目名称" />
      </el-form-item>
      <el-form-item
        prop="description"
        label="项目描述（每一项描述以英文逗号分隔）"
      >
        <el-input
          v-model="form.description"
          placeholder="项目描述（每一项描述以英文逗号分隔）"
        />
      </el-form-item>
      <el-form-item prop="url" label="项目链接">
        <el-input v-model="form.url" placeholder="项目链接" />
      </el-form-item>
      <el-form-item prop="github" label="github">
        <el-input v-model="form.github" placeholder="github" />
      </el-form-item>
      <el-form-item prop="thumb" label="预览图">
        <Upload v-model="form.thumb" placeholder="预览图" />
      </el-form-item>
      <el-form-item label="排序" prop="order">
        <el-select v-model="form.order" placeholder="排序">
          <el-option
            v-for="order in orders"
            :value="order"
            :label="order"
            :key="order"
          />
        </el-select>
      </el-form-item>
    </el-form>

    <div class="dialog-footer">
      <el-button @click="reset">重 置</el-button>
      <el-button type="primary" @click="handleConfirm">确 定</el-button>
    </div>
  </div>
</template>

<script>
import Upload from "@/components/Upload";
import { addProject } from "@/api/project";

export default {
  name: "AddProject",
  components: { Upload },
  data() {
    return {
      orders: ["1", "2", "3", "4", "5"],
      form: {
        name: "",
        description: "",
        url: "",
        github: "",
        thumb: "",
        order: "",
      },
      formRules: {
        name: [{ required: true, message: "请输入项目名称", trigger: "blur" }],
        description: [
          { required: true, message: "请输入项目描述", trigger: "blur" },
        ],
        url: [{ required: true, message: "请输入项目url", trigger: "blur" }],
        order: [
          { required: true, message: "请选择项目排序", trigger: "change" },
        ],
      },
    };
  },
  methods: {
    reset() {
      this.$refs.formRef.resetFields();
    },
    handleConfirm() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          addProject({
            ...this.form,
            description: this.form.description.split(","),
            order: +this.form.order,
          }).then(() => {
            this.$message.success("添加项目成功");
            this.$router.push("/projectsList");
          });
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.add-project-container {
  padding: 20px;
  .dialog-footer {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
